import router from "./router";
import { getToken } from "@/utils/authLib";
import type { RouteLocationNormalized } from "vue-router";
import { store } from "@/store/index";
import { useAuthStore } from "@/store/modules/auth";
const authStore = useAuthStore(store);

/**
 * @description: 设置标题
 * @param {RouteLocationNormalized} to
 * @return {*}
 */
const setPageTitle = (to: RouteLocationNormalized) => {
  const sys = authStore.systemName;
  if (to.meta && to.meta.name) {
    document.title = `${to.meta.name}${sys ? " - " + sys : ""}`;
    return;
  }
  document.title = `${sys}`;
};

const whiteList = ["/login", "/redirect"];
router.beforeEach(async (to, _from, next) => {
  setPageTitle(to);
  const hasToken = getToken();
  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      // if (authStore.id) {
      next();
      // } else {
      //   try {
      //     await authStore.getLoginUserInfo();
      //     next({ ...to, replace: true });
      //   } catch {
      //     await authStore.logout();
      //     next({
      //       path: "/login",
      //       query: { redirect: to.fullPath === "/" ? undefined : to.fullPath }
      //     });
      //   }
      // }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      // await authStore.logout();
      next({
        path: "/login",
        query: { redirect: to.fullPath === "/" ? undefined : to.fullPath }
      });
    }
  }
});
